package com.test09.gson01;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.reflect.TypeToken;

/*
 * 测试Gson的双向转
 * 总结：
 *     1.非常好用，json->bean的时候只设置一个Type对象就可以
 *     2.现在实现的是List<StudentBean>  StudentBean中有：List<CourseBean>
 *     										       Map<String, CourseBean>
 *     3.想要排除掉某些字段，方式：
 *     		1.在字段上使用transient修饰，比如：private transient Integer age;，然后还是new Gson()来创建对象
 *     		2.在字段上使用
 */
public class GsonTest {
	private ArrayList<StudentBean> studentBeans;
	private String json;
	@Before
	public void init(){
//		创建对象studentBean1，并填充属性
		StudentBean studentBean1 = new StudentBean();
		
		studentBean1.setName("wang1");
		studentBean1.setAge(10);
		
		ArrayList<CourseBean> arrayList = new ArrayList<CourseBean>();
		arrayList.add(new CourseBean("eng"));
		arrayList.add(new CourseBean("math"));
		studentBean1.setCourseBeans(arrayList);
		
		HashMap<String, CourseBean> map = new HashMap<>();
		map.put("k1", new CourseBean("eng"));
		map.put("k2", new CourseBean("math"));
		studentBean1.setMap(map);
		
		
//		创建对象studentBean2，并填充属性
		StudentBean studentBean2 = new StudentBean();
		
		studentBean2.setName("wang2");
		studentBean2.setAge(10);
		
		ArrayList<CourseBean> arrayList2 = new ArrayList<CourseBean>();
		arrayList2.add(new CourseBean("eng"));
		arrayList2.add(new CourseBean("math"));
		studentBean2.setCourseBeans(arrayList2);
		
		HashMap<String, CourseBean> map2 = new HashMap<>();
		map2.put("k1", new CourseBean("eng"));
		map2.put("k2", new CourseBean("math"));
		studentBean2.setMap(map2);
		
//		加入到list中
		ArrayList<StudentBean> arrayList3 = new ArrayList<>();
		arrayList3.add(studentBean1);
		arrayList3.add(studentBean2);
		
		this.studentBeans = arrayList3;
	}
	/*
	 * 这是bean->json
	 */
	@Test
	public void bean2Json() {
		this.json = new Gson().toJson(this.studentBeans);
		System.out.println(this.json);
	}
	
	/*
	 * json->bean
	 */
	@Test
	public void json2Bean(){
		bean2Json();
		
		Type type = new TypeToken<List<StudentBean>>(){}.getType();
		
		List<StudentBean> list = new Gson().fromJson(this.json, type);
		
		System.out.println(list);
	}
	
	/*
	 * 这是bean->json 使用transient修饰属性，排除掉某个字段,这里把age去掉了
	 */
	@Test
	public void bean2JsonExclude() {
		Gson gson = new Gson();
		
//		进行处理
		this.json =gson.toJson(this.studentBeans);
		System.out.println(this.json);
	}
	
	/*
	 * 这是bean->json 使用@Expose修饰属性，没有修饰的不会导出,这里只修饰了name
	 */
	@Test
	public void bean2JsonExclude2() {
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		
//		进行处理
		this.json =gson.toJson(this.studentBeans);
		System.out.println(this.json);
	}
}
